package com.bupt.service;

import com.bupt.bean.Event;
import com.bupt.bean.MessageMgt;
import com.bupt.config.Result;
import com.bupt.dao.EventRepository;
import com.bupt.dao.MessageMgtRepository;
import com.bupt.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class EventService {

    @Autowired
    private EventRepository eventRepository;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private PrimaryKeyService primaryKeyService;

    @Autowired
    MessageMgtRepository messageMgtRepository;

    //统计报警日期和条数信息  暂时是显示前7天的数据
    public List getEventAndCount() {
        //结果集合
        List eventCountList = new ArrayList<>();
        //结果集的子集 横纵坐标集合
        ArrayList<String> valueList = new ArrayList<>();
        ArrayList<String> timeList = new ArrayList<>();
        ArrayList<String> timeList1 = new ArrayList<>();
        //获取7天前日期和昨日日期
        String nowTime = DateUtils.getPastDate(0);
        String oneTimeAge = DateUtils.getPastDate(1);
        String twoTimeAge = DateUtils.getPastDate(2);
        String threeTimeAge = DateUtils.getPastDate(3);
        String fourTimeAge = DateUtils.getPastDate(4);
        String fiveTimeAge = DateUtils.getPastDate(5);
        String sixTimeAge = DateUtils.getPastDate(6);
        String sevenTimeAge = DateUtils.getPastDate(7);
        //前台需要切割的时间结果集
        timeList.add(sevenTimeAge.substring(5, 10));
        timeList.add(sixTimeAge.substring(5, 10));
        timeList.add(fiveTimeAge.substring(5, 10));
        timeList.add(fourTimeAge.substring(5, 10));
        timeList.add(threeTimeAge.substring(5, 10));
        timeList.add(twoTimeAge.substring(5, 10));
        timeList.add(oneTimeAge.substring(5, 10));
        //后台需要用的时间结果集
        timeList1.add(sevenTimeAge);
        timeList1.add(sixTimeAge);
        timeList1.add(fiveTimeAge);
        timeList1.add(fourTimeAge);
        timeList1.add(threeTimeAge);
        timeList1.add(twoTimeAge);
        timeList1.add(oneTimeAge);
        //循环7次查询结果集
        Query nativeQuery = null;
        for (int i = 0; i < timeList1.size(); i++) {
            if (i == timeList1.size() - 1) {
                String sql = "SELECT COUNT(*)AS COUNT  FROM event_t e WHERE e.creat_time BETWEEN  ('" + timeList1.get(i) + "') AND ('" + nowTime + "')";

                nativeQuery = entityManager.createNativeQuery(sql);
                String s = nativeQuery.getResultList().get(0).toString();
                valueList.add(s);
            } else {
                String sql = "SELECT COUNT(*)AS COUNT  FROM event_t e WHERE e.creat_time BETWEEN  ('" + timeList1.get(i) + "') AND ('" + timeList1.get(i + 1) + "')";

                nativeQuery = entityManager.createNativeQuery(sql);
                String s = nativeQuery.getResultList().get(0).toString();
                valueList.add(s);
            }
        }

        eventCountList.add(valueList);
        eventCountList.add(timeList);


        return eventCountList;
    }


    //将所有报警改为已处理状态
    public Result editEventStatus() {
        Result result = new Result();
        String sql="UPDATE event_t SET STATUS=2 WHERE STATUS=1";
        Query nativeQuery = entityManager.createNativeQuery(sql);
        //message
        String messagesql="SELECT c.device_id FROM \n" +
                "(SELECT DISTINCT e.device_id FROM event_t e  \n" +
                "WHERE e.status=1 \n" +
                ")d, (SELECT dt.device_type_id,d.device_id FROM device_type_t dt,device_t d  WHERE dt.device_type_id=d.device_type_id)c\n" +
                " WHERE c.device_id=d.device_id \n" +
                "AND c.device_type_id=2";
        Query nativeQuerymessage = entityManager.createNativeQuery(messagesql);
        List resultList = nativeQuerymessage.getResultList();
        if(resultList.size()!=0){
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            for (int j = 0; j <resultList.size() ; j++) {
                String deviceId = resultList.get(j).toString();
                MessageMgt m = new MessageMgt();
                Integer ids = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                m.setMessageMgtId(ids);
                m.setDeviceId(Integer.valueOf(deviceId));
                String ipsql = "SELECT device_ip FROM device_network_t WHERE device_id="+deviceId;
                Query nativeQueryip = entityManager.createNativeQuery(ipsql);
                String ip = nativeQueryip.getResultList().get(0).toString();
                m.setDeviceIp(ip);
                m.setMsgType(222);
                m.setMsgBody("");
                m.setState(0);
                m.setRepeatNum(0);
                m.setCreateTime(timestamp);
                messageMgtRepository.save(m);
            }
        }
        int i = nativeQuery.executeUpdate();
        if(i==0){

            result.setResult("清除失败");
            result.setCode(404);
        }else {
            result.setResult("清除成功");
            result.setCode(200);
        }
            return  result;
    }

    //将指定ID报警改为已处理状态
    public Result editEventStatuById(Integer eventId) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Event event = eventRepository.findByEventId(eventId);
        Integer channelSectionId = event.getChannelSectionId();
        Result result = new Result();
        String sql="UPDATE event_t SET STATUS=2 WHERE STATUS=1 and event_id="+eventId;
        Query nativeQuery = entityManager.createNativeQuery(sql);
        int i = nativeQuery.executeUpdate();
        String sqlmessage="SELECT device_type_id FROM device_t d WHERE d.device_id=\n" +
                "(SELECT device_id FROM event_t e WHERE e.event_id="+eventId+")";
        Query nativeQuerymessage = entityManager.createNativeQuery(sqlmessage);
        List resultList = nativeQuerymessage.getResultList();
        if(resultList.size()!=0){
                String othersql="SELECT event_id FROM event_t e WHERE e.status=1 " +
                        "AND channel_section_id="+channelSectionId+" AND event_id !="+eventId;
            Query nativeQueryother = entityManager.createNativeQuery(othersql);
            List resultList1 = nativeQueryother.getResultList();
            if(resultList1.size()==0){
                String endpointsql="SELECT ENDPOINT FROM channel_section_t WHERE channel_section_id="+channelSectionId;
                Query nativeQueryendpoint = entityManager.createNativeQuery(endpointsql);
                List endpointtList = nativeQueryendpoint.getResultList();
                if (endpointtList.size() > 0) {
                    String s = endpointtList.get(0).toString();
                    String[] endpointarr = s.split(",");
                    for (int j = 0; j <endpointarr.length ; j++) {
                        MessageMgt m = new MessageMgt();
                        Integer ids = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                        m.setMessageMgtId(ids);
                        m.setDeviceId(Integer.valueOf(event.getDeviceId()));
                        String ipsql = "SELECT device_ip FROM device_network_t WHERE device_id=1556";
                        Query nativeQueryip = entityManager.createNativeQuery(ipsql);
                        String ip = nativeQueryip.getResultList().get(0).toString();
                        m.setDeviceIp(ip);
                        m.setMsgType(31);
                        m.setMsgBody(endpointarr[j]);
                        m.setState(0);
                        m.setRepeatNum(0);
                        m.setCreateTime(timestamp);
                        messageMgtRepository.save(m);
                    }
                }else {
                    MessageMgt m = new MessageMgt();
                    Integer ids = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    m.setMessageMgtId(ids);
                    m.setDeviceId(Integer.valueOf(event.getDeviceId()));
                    String ipsql = "SELECT device_ip FROM device_network_t WHERE device_id=" + event.getDeviceId();
                    Query nativeQueryip = entityManager.createNativeQuery(ipsql);
                    String ip = nativeQueryip.getResultList().get(0).toString();
                    m.setDeviceIp(ip);
                    m.setMsgType(31);
                    m.setMsgBody("14");
                    m.setState(0);
                    m.setRepeatNum(0);
                    m.setCreateTime(timestamp);
                    messageMgtRepository.save(m);
                }
             }
        }

        if(i==0){

            result.setResult("清除失败");
        }else {
            result.setResult("清除成功");
        }
        return  result;
    }
    //标记误报
    public Result editEventFlagById(Integer eventId) {
        Result result = new Result();
        String sql="UPDATE event_t SET error_flag=1 WHERE error_flag=0 AND  event_id="+eventId;
        Query nativeQuery = entityManager.createNativeQuery(sql);
        int i = nativeQuery.executeUpdate();
        if(i==0){

            result.setResult("标记失败");
        }else {
            result.setResult("标记成功");
        }
        return  result;
    }

}
